<template>
  <div class="application-list-container container-min-height">
    <div class="flex-between mb-16">
      <div class="flex-between">
        <el-space>
          <!-- 搜索框 -->
          <el-input
            v-model="searchForm.name"
            placeholder="智能体名称"
            prefix-icon="Search"
            class="w-240 search-input"
            style="max-width: 240px"
            clearable
             @input="handleDebounceSearch"
          />
          <el-select
            v-model="searchForm.type"
            placeholder="应用类型"
            style="width: 160px"
            clearable
            @change="searchHandle"
          >
            <el-option
              v-for="item in applicationTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select
            v-model="searchForm.authState"
            placeholder="选择可见范围"
            style="width: 160px"
            clearable
            @change="searchHandle"
          >
            <el-option
              v-for="item in authOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select
            v-model="searchForm.classification"
            placeholder="选择分类"
            style="width: 160px"
            @change="searchHandle"
            clearable
          >
            <el-option
              v-for="item in perTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-space>

        <!-- <el-button
          type="primary"
          class="ml-12"
          @click.stop="searchHandle"
        >
          筛选
        </el-button> -->
      </div>
      <!-- 新增按钮 -->
      <div class="flex-between">
          <el-button
            type="primary"
            :icon="Plus"
            class="ml-12"
            @click="openCreateDialog"
          >
            创建智能体
          </el-button>
        </div>
    </div>

    <div
        v-loading="loading"
        element-loading-text="正在加载..."
        style="width: 100%"
        class="loading-page"
        v-if="loading"
    ></div>
    <PageEmpty v-else-if="!applicationList.length && !loading" :type="pageEmptyType" />
    <!-- 头部搜索-->
    <app-table
      v-else
      ref="multipleTableRef"
      class="mt-16"
      :data="applicationList"
      :pagination-config="paginationConfig"
      @sizeChange="handleSizeChange"
      @changePage="getList"
    >
      <el-table-column prop="name" label="序号" min-width="60">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="imgUrl" label="智能体头像" min-width="100">
        <template #default="{row}">
            <img
              :src="row.imgUrl ? row.imgUrl : defImg"
              class="avatar-img"
              style="width: 40px; height: 40px"
            />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="智能体名称" min-width="180">
        <template #default="{ row }">
          <AutoTooltip style="color:#3067EF ;">
            {{ row.name }}
          </AutoTooltip>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="" width="100">
        <template #header>
          启用状态
          <el-tooltip content="启用后，在智能体可见">
            <el-icon><Warning /></el-icon>
          </el-tooltip>
        </template>
        <template #default="{ row }">
          <el-switch v-model="row.state"  @change="handelSwitch(row)" :disabled="row.createdBy !== dada.id"/>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="应用类型" min-width="100">
        <template #default="{ row }">
            <el-tag type="warning" style="height: 22px" v-if="row.type === 'WORK_FLOW'" >
              高级编排
            </el-tag>
            <el-tag class="blue-tag" style="height: 22px" v-else>
              简单配置
            </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="可见范围" min-width="150">
        <template #default="{ row }">
          <AutoTooltip>
            {{ getAuthLabel(row.authState) }}
          </AutoTooltip>
        </template>
      </el-table-column>
      <el-table-column prop="classification" label="所属分类" min-width="120">
        <template #default="{ row }">
          <AutoTooltip>
            {{ mapClassification[row.classification] }}
          </AutoTooltip>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" width="165" sortable>
        <template #default="{ row }">
          <AutoTooltip>
            {{ datetimeFormat(row.createdTime) }}
          </AutoTooltip>
        </template>
      </el-table-column>
      <el-table-column prop="updatedTime" label="更新时间" width="165" sortable>
        <template #default="{ row }">
          <AutoTooltip>
            {{ datetimeFormat(row.updatedTime) }}
          </AutoTooltip>
        </template>
      </el-table-column>
      <el-table-column prop="createdByName" label="创建人" width="100">
        <template #default="{ row }">
          <AutoTooltip>
            {{ row.createdByName }}
          </AutoTooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="120" fixed="right">
        <template #default="{ row }">
          <div >
            <span class="mr-10 primary-text">
              <el-tooltip
                effect="dark"
                content="预览"
                placement="top"
              >
                <el-icon @click.stop="jumpToChat(row)"><Tickets /></el-icon>
              </el-tooltip>
            </span>
            <!-- 创建人是当前登录人 才显示编辑按钮 -->
            <span class="mr-10 primary-text" v-if="row.createdBy === dada.id">
              <el-tooltip
                effect="dark"
                content="编辑"
                placement="top"
              >
                <el-icon @click.stop="openEditDialog(row)"><EditPen /></el-icon>
              </el-tooltip>
            </span>
            <!-- 创建人是当前登录人 才显示设置按钮 -->
            <span class="mr-10 primary-text" v-if="row.createdBy === dada.id">
              <el-tooltip
                effect="dark"
                content="设置"
                placement="top"
              >
                <el-icon @click.stop="settingApplication(row)"><Setting /></el-icon>
              </el-tooltip>
            </span>
            <!-- <span class="mr-10 primary-text">
              <el-tooltip
                effect="dark"
                content="复制"
                placement="top"
              >
                <el-icon @click.stop="copyApplication(row)"><CopyDocument /></el-icon>
              </el-tooltip>
            </span> -->
            <!-- 创建人是当前登录人 才显示删除按钮 -->
<!--            <span class="mr-10" v-if="row.createdBy === dada.id">
              <el-tooltip
                effect="dark"
                content="删除"
                placement="top"
              >
                <el-icon @click.stop="deleteApplication(row)"><Delete /></el-icon>
              </el-tooltip>
            </span>-->
            <el-dropdown trigger="click" type="primary">
              <span class="mr-10 primary-text" style="position: relative; top: 2px; cursor: pointer;">
                <el-icon>
                  <MoreFilled />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu class="avatar-dropdown">
                  <el-dropdown-item @click.stop="copyApplication(row)">
                    复制
                  </el-dropdown-item>
                  <el-dropdown-item @click.stop="handleMoveUp(row)">
                    上移
                  </el-dropdown-item>
                  <el-dropdown-item @click.stop="handleMoveDown(row)">
                    下移
                  </el-dropdown-item>
                  <el-dropdown-item @click.stop="deleteApplication(row)" v-if="row.createdBy === dada.id">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </app-table>
    <CreateApplicationDialog ref="CreateApplicationDialogRef"  @refresh="getList"/>
    <CopyApplicationDialog ref="CopyApplicationDialogRef" @refresh="getList" />
    <EditApplicationDialog ref="EditApplicationDialogRef" @refresh="getList" />
  </div>
</template>
<script setup lang="ts">
import AppTable from '@/components/app-table/index.vue'
import AutoTooltip from '@/components/auto-tooltip/index.vue'
import { ref, onMounted, reactive } from 'vue'
import CreateApplicationDialog from './component/CreateApplicationDialog.vue'
import EditApplicationDialog from './component/EditApplicationDialog.vue'
import CopyApplicationDialog from './component/CopyApplicationDialog.vue'
import { MsgSuccess, MsgConfirm, MsgError } from '@/utils/message'
import { useRouter } from 'vue-router'
import { isWorkFlow } from '@/utils/application'
import useStore from '@/stores'
import { datetimeFormat } from '@/utils/time'
 import { Plus } from '@element-plus/icons-vue'
 import { applicationTypeOptions } from '@/enums/application'
 import { authOptions } from '@/enums/application'
 import { delAiApplication, applicationConfigPage, updateApplicationState, updateApplicationSortValue } from '@/servers/ai/api/zhinengti'
 import defImg  from '@/assets/agent/def_agent.svg'
import { debounce, find } from 'lodash'

function getAuthLabel (value: number) {
  return (find(authOptions, (v: any) => v.value === value) || {}).label || ''
}


const { application, agent, dada } = useStore()
const router = useRouter()

const CopyApplicationDialogRef = ref()
const CreateApplicationDialogRef = ref()
const EditApplicationDialogRef = ref()
const loading = ref(true)
const pageEmptyType = ref('1')

const applicationList = ref<any[]>([])
const perTypeList: any = ref([])
const paginationConfig = reactive({
  current_page: 1,
  page_size: 10,
  total: 0
})
const searchForm = ref<any>({
  name: '', // 名称
  classification: '', // 分类
  type: '', // 智能体类型-枚举,可用值:SIMPLE,WORK_FLOW
  authState: '', 	// 授权状态;[0-仅自己可见 1-自定义课件范围]
});
const mapClassification = ref<any>({})

function jumpToChat(item: any) {
  localStorage.setItem('avatar', item.imgUrl || '')
  localStorage.setItem('renderingType', item.renderingType || '')
  if (item.tyType === 1) {
    router.push('/agent/chat/' + item.maxTyTypeUrl)
    return
  }
  application.asyncGetAccessToken(item.maxId, loading).then((res: any) => {
    // const shareUrl = '/agent/chat?accessToken=' + res?.data?.access_token + '&application_id=' + res?.data?.application_id
    const shareUrl = '/agent/chat/' + res?.data?.access_token
    router.push(shareUrl)
  })
}

// 复制
function copyApplication(row: any) {
  CopyApplicationDialogRef.value.open(row)
}
async function handleMoveUp (row: any) {
  loading.value = true
  updateApplicationSortValue({ id: row.id, sortState: -1 })
    .then(() => {
      MsgSuccess('上移成功')
      getList()
    })
    .catch((err: any) => {
      MsgError(err.response.data.msg)
    })
    .finally(() => {
      loading.value = false
    })
}
async function handleMoveDown (row: any) {
  loading.value = true
  updateApplicationSortValue({ id: row.id, sortState: 1 })
    .then(() => {
      MsgSuccess('下移成功')
      getList()
    })
    .catch((err: any) => {
      MsgError(err.response.data.msg)
    })
    .finally(() => {
      loading.value = false
    })
}

const handleDebounceSearch = debounce(() => {
  searchHandle()
},500)

function handleSizeChange() {
  paginationConfig.current_page = 1
  getList()
}

function openCreateDialog() {
  CreateApplicationDialogRef.value.open()
}

function openEditDialog(row: any) {
  EditApplicationDialogRef.value.open(row)
}

function searchHandle() {
  applicationList.value = []
  paginationConfig.current_page = 1
  paginationConfig.total = 0
  getList()
}

// 删除
function deleteApplication(row: any) {
  MsgConfirm(
    // @ts-ignore
    `是否删除智能体 ${row.name} ?`,
    '删除后该智能体将不再提供服务，请谨慎操作。',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      loading.value = true
      delAiApplication({ id: row.id }).then(() => {
        MsgSuccess('删除成功')
      })
      .catch((err) => {
        MsgError(err.response.data.msg)
      })
      .finally(() => {
        loading.value = false
        getList()
      })
    })
    .catch(() => {})
}

// 设置
function settingApplication(row: any) {
  if (isWorkFlow(row.type)) {
    router.push({ path: `/application/${row.maxId}/workflow` })
  } else {
    router.push({ path: `/application/${row.maxId}/${row.type}/setting` })
  }
}

// 启用状态
function handelSwitch(row: any) {
  loading.value = true
  updateApplicationState({ id: row.id, state: row.state }).then((res: any) => {
    MsgSuccess('修改成功')
  }).catch((err) => {
    MsgError(err.response.data.msg)
  }).finally(() => {
    loading.value = false
    getList()
  })
}

function getList() {
  // if(loading.value) return
  const params: any = {
    "model": {
      ...searchForm.value
    },
    "size": paginationConfig.page_size,
    "current": paginationConfig.current_page,
  }
  params.model.classification === 'all' && delete params.model.classification
  if (searchForm.value.name) {
    pageEmptyType.value = '2'
  } else {
    pageEmptyType.value = '1'
  }
  loading.value = true
  applicationConfigPage(params).then((res: any) => {
    if (res.data.isSuccess) {
      const { records, total } = res.data.data
      applicationList.value = [ ...records]
      paginationConfig.total = Number(total)
    }
  }).catch(() => {
      pageEmptyType.value = '3'
  }).finally(() => {
    loading.value = false
  })
}

async function getOptions () {
  const options = await agent.getCategorizeOptions()
  const MapArr: any = {}
  options.forEach((item: any) => {
    MapArr[item.value] = item.label
  })
  mapClassification.value = MapArr
  perTypeList.value = [ {label: "全部", value: "all"}, ...options]

}

onMounted(async() => {
  getOptions()
  getList()
})
</script>
<style lang="scss" scoped>
.application-list-container {
  min-height: 500px;
  box-sizing: border-box;
  padding-bottom: 30px;
  position: relative;
  .loading-page {
    position: absolute;
    top: 50%;
    margin-top: -18px;
  }
}
.application-card-add {
  width: 100%;
  font-size: 14px;
  min-height: var(--card-min-height);
  border: 1px dashed var(--el-border-color);
  background: var(--el-disabled-bg-color);
  border-radius: 8px;
  box-sizing: border-box;

  &:hover {
    border: 1px solid var(--el-card-bg-color);
    background-color: var(--el-card-bg-color);
  }

  .card-add-button {
    &:hover {
      border-radius: 4px;
      background: var(--app-text-color-light-1);
    }

    :deep(.el-upload) {
      display: block;
      width: 100%;
      color: var(--el-text-color-regular);
    }
  }
}

.application-card {
  .status-tag {
    position: absolute;
    right: 16px;
    top: 15px;
  }
}

.dropdown-custom-switch {
  padding: 5px 11px;
  font-size: 14px;
  font-weight: 400;

  span {
    margin-right: 26px;
  }
}
</style>
